//
//  HMOauthViewController.swift
//  HMWeibo12
//
//  Created by iOS on 16/9/17.
//  Copyright © 2016年 iOS. All rights reserved.
//

import UIKit
import SVProgressHUD

// Eclipse
class HMOauthViewController: UIViewController {
    
    override func loadView() {
        self.view = webView
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = HMDefaultBackgroundColor
        setupNavigation()
        
        // 使用WebView去加载网页(登录界面)
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        print("urlString = \(urlString)")
        let url = URL(string: urlString)!
        let urlRequest = URLRequest(url: url)
        webView.loadRequest(urlRequest)
        
        // 提示用户
        SVProgressHUD.show(withStatus: "正在加载登录界面...")
    }
    
    private func setupNavigation() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(autoFill))
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(close))
    }
    
    // MARK: - 按钮点击事件
    func close() -> Void {
        SVProgressHUD.dismiss()
        self.dismiss(animated: true, completion: nil)
    }
    
    func autoFill() -> Void {
        print("autoFill")
        let jsCode = "document.getElementById('userId').value='czbkiosweibo@163.com';document.getElementById('passwd').value='czbkios111';"
        
        // 让webView执行js代码
        webView.stringByEvaluatingJavaScript(from: jsCode)
    }
    
    // MARK: - 懒加载
    private lazy var webView: UIWebView = UIWebView()
}

extension HMOauthViewController: UIWebViewDelegate {
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    // webView在加载网络地址之前会询问我们是否正的要去加载
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        print("request: \(request)")
        let urlString = request.url!.absoluteString
        print("urlString = \(urlString)")
        
        // 点击取消: http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        // 点击授权: http://www.baidu.com/?code=55a1482b0e76325ecb4b2f22b5c8be14

        if !urlString.hasPrefix(redirect_uri) {
            // 不是授权回调地址开头,普通的网络请求,去加载
            return true
        } else {
            // 是授权回调地址
            print("是授权回调地址")
            // 判断点击的是取消或授权,看?后面是否是code=开头
            let query = request.url?.query
            print("query: \(query)")
            let codeString = "code="
            if query!.hasPrefix(codeString) {
                // 授权, 截取code= 后面的字符串
                let nsQuery = query! as NSString
                
                let code = nsQuery.substring(from: codeString.characters.count)
                print("截取到的code: \(code)")
                // 发送POST请求获取AccessToken
                HMUserAccountVM.shared.loadAccessToken(code: code, completion: { (error: Error?) in
                    
                    if error != nil {
                        print("加载AccessToken出错了: \(error)")
                        SVProgressHUD.showError(withStatus: "你的网络不给力...")
                        
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2, execute: {
                            self.close()
                        })
                        
                        return
                    }
                    
                    // 加载成功了
                    print("加载成功了")
                    self.close()
                    
                    // 跳转到欢迎界面,切换AppDelegate的window属性的根控制器
                    UIApplication.shared.keyWindow?.rootViewController = HMWelcomeViewController()
                })
            } else {
                // 取消, 直接关闭控制器
                close()
            }
            
            return false
        }
    }
    
}
